<?php
/**
 * VIP会员逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\logic;

use app\common\logic\LogicBase;

class Vip extends LogicBase
{
    /**
     * 获取VIP套餐搜索条件
     */
    public function getVipPackageWhere($data = [])
    {
        $where = [];
        
        // 套餐类型搜索
        !empty($data['type']) && $where['type'] = $data['type'];
        
        // 状态搜索
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 套餐名称搜索
        !empty($data['search_data']) && $where['name'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 价格范围搜索
        if (isset($data['min_price']) && $data['min_price'] !== '') {
            $where['price'] = ['>=', $data['min_price']];
        }
        if (isset($data['max_price']) && $data['max_price'] !== '') {
            if (isset($where['price'])) {
                $where['price'] = ['between', [$data['min_price'], $data['max_price']]];
            } else {
                $where['price'] = ['<=', $data['max_price']];
            }
        }
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        return $where;
    }

    /**
     * 获取VIP订单搜索条件
     */
    public function getVipOrderWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 套餐类型搜索
        !empty($data['package_type']) && $where['package_type'] = $data['package_type'];
        
        // 支付状态搜索
        isset($data['pay_status']) && $data['pay_status'] !== '' && $where['pay_status'] = $data['pay_status'];
        
        // 订单状态搜索
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 订单号搜索
        !empty($data['order_no']) && $where['order_no'] = ['like', '%' . $data['order_no'] . '%'];
        
        // 套餐名称搜索
        !empty($data['search_data']) && $where['package_name'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日订单筛选（用于后台首页"今日订单"链接）
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 获取VIP订单搜索条件（兼容旧方法）
     * @deprecated 请使用 getVipOrderWhere() 方法
     */
    public function getWhere($data = [])
    {
        return $this->getVipOrderWhere($data);
    }
    
    /**
     * 获取VIP套餐搜索条件（兼容控制器调用）
     * @deprecated 请使用 getVipPackageWhere() 方法
     */
    public function getPackageWhere($data = [])
    {
        return $this->getVipPackageWhere($data);
    }
    
    /**
     * 获取VIP套餐列表
     */
    public function getVipPackages($data = [])
    {
        try {
            $where = ['status' => 1];
            $field = 'id,name,type,duration_days,price,original_price,description,features,sort';
            $order = 'sort asc,id asc';
            
            $list = $this->modelVipPackage->getList($where, $field, $order, false);
            
            // 处理特性列表和数据格式化
            foreach ($list as $key => $item) {
                // 解析JSON格式的特性列表
                $item['features'] = $item['features'] ? json_decode($item['features'], true) : [];
                
                // 添加套餐类型中文名称
                $typeNames = [
                    'month' => '月度会员',
                    'year' => '年度会员', 
                    'three_year' => '三年会员'
                ];
                $item['type_name'] = $typeNames[$item['type']] ?? $item['name'];
                
                // 计算折扣信息
                if ($item['original_price'] > $item['price']) {
                    $item['discount'] = round(($item['price'] / $item['original_price']) * 10, 1);
                    $item['save_amount'] = $item['original_price'] - $item['price'];
                } else {
                    $item['discount'] = 10;
                    $item['save_amount'] = 0;
                }
                
                // 计算每日价格
                $item['daily_price'] = round($item['price'] / $item['duration_days'], 2);
                
                // 推荐标识（年度会员推荐）
                $item['is_recommended'] = ($item['type'] == 'year');
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户VIP信息（基于VIP订单表和用户表）
     */
    public function getUserVipInfo($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 先从用户表获取VIP信息
            $userInfo = $this->modelUser->getInfo(['id' => $userId], 'vip_level,vip_start_time,vip_expire_time');
            
            if ($userInfo && $userInfo['vip_level'] > 0 && !empty($userInfo['vip_expire_time'])) {
                $expireTime = strtotime($userInfo['vip_expire_time']);
                $isVip = $expireTime > time();
                
                if ($isVip) {
                    // 获取最近的VIP订单信息
                    $where = [
                        'user_id' => $userId,
                        'order_status' => 1  // 已支付
                    ];
                    $field = 'id,package_type,package_name,amount,pay_time';
                    $order = 'pay_time desc';
                    
                    $vipOrder = $this->modelVipOrder->getInfo($where, $field, $order);
                    
                    $result = [
                        'is_vip' => true,
                        'order_id' => $vipOrder['id'] ?? 0,
                        'package_type' => $vipOrder['package_type'] ?? '',
                        'package_name' => $vipOrder['package_name'] ?? '',
                        'start_time' => $userInfo['vip_start_time'],
                        'end_time' => $userInfo['vip_expire_time'],
                        'amount' => $vipOrder['amount'] ?? 0,
                        'remaining_days' => ceil(($expireTime - time()) / 86400)
                    ];
                } else {
                    $result = [
                        'is_vip' => false,
                        'order_id' => 0,
                        'package_type' => '',
                        'package_name' => '',
                        'start_time' => '',
                        'end_time' => '',
                        'amount' => 0,
                        'remaining_days' => 0
                    ];
                }
            } else {
                $result = [
                    'is_vip' => false,
                    'order_id' => 0,
                    'package_type' => '',
                    'package_name' => '',
                    'start_time' => '',
                    'end_time' => '',
                    'amount' => 0,
                    'remaining_days' => 0
                ];
            }
            
            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 创建VIP订单
     */
    public function createVipOrder($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $packageId = $data['package_id'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if (!$packageId) {
                return [RESULT_ERROR, '套餐ID不能为空'];
            }
            
            // 获取套餐信息
            $package = $this->modelVipPackage->getInfo(['id' => $packageId, 'status' => 1]);
            if (!$package) {
                return [RESULT_ERROR, '套餐不存在或已下架'];
            }
            
            // 生成订单号
            $orderNo = 'VIP' . date('YmdHis') . rand(1000, 9999);
            
            // 直接使用套餐表中的type字段作为package_type
            $packageType = $package['type'] ?? 'month';
            
            // 计算VIP开始和结束时间
            $currentTime = time();
            
            // 检查用户当前VIP状态，如果已是VIP且未过期，则从过期时间开始计算
            $userInfo = $this->modelUser->getInfo(['id' => $userId], 'vip_expire_time');
            $startTime = $currentTime;
            if ($userInfo && !empty($userInfo['vip_expire_time'])) {
                $currentExpireTime = strtotime($userInfo['vip_expire_time']);
                if ($currentExpireTime > $currentTime) {
                    $startTime = $currentExpireTime; // 从当前过期时间开始延期
                }
            }
            
            // 根据套餐类型计算结束时间
            $endTime = $startTime;
            switch ($packageType) {
                case 'month':
                    $endTime = strtotime('+1 month', $startTime);
                    break;
                case 'quarter':
                    $endTime = strtotime('+3 months', $startTime);
                    break;
                case 'year':
                    $endTime = strtotime('+1 year', $startTime);
                    break;
                case 'three_year':
                    $endTime = strtotime('+3 years', $startTime);
                    break;
            }
            
            // 创建VIP订单记录（包含时间字段）
            $vipData = [
                'user_id' => $userId,
                'order_no' => $orderNo,
                'package_type' => $packageType,
                'package_name' => $package['name'],
                'amount' => $package['price'],
                'inviter_id' => $data['inviter_id'] ?? 0,
                'commission' => $data['commission'] ?? 0,
                'order_status' => 0, // 待支付
                'transaction_id' => '',
                'start_time' => $startTime,
                'end_time' => $endTime,
                'create_time' => time(),
                'pay_time' => 0,
                'update_time' => time()
            ];
            
            $vipId = $this->modelVipOrder->updateInfo([], $vipData);
            
            if ($vipId) {
                $result = [
                    'vip_id' => $vipId,
                    'order_no' => $orderNo,
                    'package_name' => $package['name'],
                    'package_type' => $packageType,
                    'price' => $package['price']
                ];
                
                return [RESULT_SUCCESS, '订单创建成功', $result];
            } else {
                return [RESULT_ERROR, '订单创建失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '创建失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 支付成功回调
     */
    public function paymentSuccess($data = [])
    {
        try {
            $orderNo = $data['order_no'] ?? '';
            $transactionId = $data['transaction_id'] ?? '';
            
            if (!$orderNo) {
                return [RESULT_ERROR, '订单号不能为空'];
            }
            
            // 获取订单信息
            $vipOrder = $this->modelVipOrder->getInfo(['order_no' => $orderNo, 'order_status' => 0]);
            if (!$vipOrder) {
                return [RESULT_ERROR, '订单不存在或已支付'];
            }
            
            // 更新支付状态
            $updateData = [
                'transaction_id' => $transactionId,
                'order_status' => 1, // 已支付
                'pay_time' => time(),
                'update_time' => time()
            ];
            
            $result = $this->modelVipOrder->updateInfo(['id' => $vipOrder['id']], $updateData);
            
            if ($result) {
                // 激活用户VIP权限
                $this->activateVipByOrder($vipOrder);
                
                // 处理邀请佣金
                $this->processInviteCommission($vipOrder);
                
                return [RESULT_SUCCESS, '支付成功'];
            } else {
                return [RESULT_ERROR, '支付状态更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '处理失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取最近充值会员列表（虚拟数据）
     */
    public function getRecentVipUsers($data = [])
    {
        try {
            $limit = $data['limit'] ?? 10;
            
            // 生成虚拟数据
            $mockUsers = [
                ['nickname' => '烟***', 'package_name' => '年度会员', 'time' => '刚刚'],
                ['nickname' => '酒***', 'package_name' => '三年会员', 'time' => '1分钟前'],
                ['nickname' => '茶***', 'package_name' => '月度会员', 'time' => '3分钟前'],
                ['nickname' => '香***', 'package_name' => '年度会员', 'time' => '5分钟前'],
                ['nickname' => '醇***', 'package_name' => '三年会员', 'time' => '8分钟前'],
                ['nickname' => '雅***', 'package_name' => '月度会员', 'time' => '10分钟前'],
                ['nickname' => '韵***', 'package_name' => '年度会员', 'time' => '12分钟前'],
                ['nickname' => '品***', 'package_name' => '三年会员', 'time' => '15分钟前'],
                ['nickname' => '味***', 'package_name' => '月度会员', 'time' => '18分钟前'],
                ['nickname' => '香***', 'package_name' => '年度会员', 'time' => '20分钟前']
            ];
            
            $result = array_slice($mockUsers, 0, $limit);
            
            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 检查用户是否为VIP
     */
    public function checkUserVip($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $vipInfo = $this->getUserVipInfo(['user_id' => $userId]);
            
            if ($vipInfo[0] == RESULT_SUCCESS) {
                return [RESULT_SUCCESS, '检查成功', ['is_vip' => $vipInfo[2]['is_vip']]];
            } else {
                return $vipInfo;
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '检查失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户VIP购买记录（基于VIP订单表）
     */
    public function getUserVipHistory($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            $where = ['user_id' => $userId];
            $field = 'id,order_no,package_type,package_name,amount,status,transaction_id,start_time,end_time,pay_time,create_time,update_time';
            $order = 'id desc';
            $paginate = ['list_rows' => $limit, 'page' => $page];
            
            $list = $this->modelVipOrder->getList($where, $field, $order, $paginate);
            
            // 处理返回数据，添加状态文本
            if ($list) {
                foreach ($list as $key => $item) {
                    $item['status_text'] = $this->getOrderStatusText($item['status']);
                    $item['payment_method'] = 'wechat'; // 默认微信支付
                    
                    // 格式化时间显示
                    $item['pay_time_text'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
                    $item['create_time_text'] = $item['create_time'] ? date('Y-m-d H:i:s', $item['create_time']) : '';
                    $item['start_time_text'] = $item['start_time'] ? date('Y-m-d H:i:s', $item['start_time']) : '';
                    $item['end_time_text'] = $item['end_time'] ? date('Y-m-d H:i:s', $item['end_time']) : '';
                    
                    // 重新赋值修改后的数据
                    $list[$key] = $item;
                }
            }
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 套餐管理
     */
    public function packageManage($data = [])
    {
        try {
            $id = $data['id'] ?? 0;
            if (!$id) {
                return [RESULT_ERROR, '套餐ID不能为空'];
            }
            
            // 移除不需要的字段
            unset($data['id']);
            
            $result = $this->modelVipPackage->updateInfo(['id' => $id], $data);
            
            if ($result) {
                return [RESULT_SUCCESS, '套餐管理成功'];
            } else {
                return [RESULT_ERROR, '套餐管理失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '套餐管理失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 套餐添加
     */
    public function packageAdd($data = [])
    {
        try {
            // 设置默认值
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['status'] = $data['status'] ?? 1;
            $data['sort'] = $data['sort'] ?? 0;
            
            $result = $this->modelVipPackage->updateInfo([], $data);
            
            if ($result) {
                return [RESULT_SUCCESS, '套餐添加成功'];
            } else {
                return [RESULT_ERROR, '套餐添加失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '套餐添加失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 套餐编辑
     */
    public function packageEdit($data = [])
    {
        try {
            $id = $data['id'] ?? 0;
            if (!$id) {
                return [RESULT_ERROR, '套餐ID不能为空'];
            }
            
            // 移除ID字段，避免更新主键
            unset($data['id']);
            
            // 设置更新时间
            $data['update_time'] = date('Y-m-d H:i:s');
            
            $result = $this->modelVipPackage->updateInfo(['id' => $id], $data);
            
            if ($result) {
                return [RESULT_SUCCESS, '套餐编辑成功'];
            } else {
                return [RESULT_ERROR, '套餐编辑失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '套餐编辑失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取套餐信息
     */
    public function getPackageInfo($where = [], $field = true)
    {
        try {
            $info = $this->modelVipPackage->getInfo($where, $field);
            
            if (!$info) {
                return [RESULT_ERROR, '套餐不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $info];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }

    /**
     * 套餐删除
     */
    public function packageDel($data = [])
    {
        try {
            $id = $data['id'] ?? 0;
            if (!$id) {
                return [RESULT_ERROR, '套餐ID不能为空'];
            }
            
            $result = $this->modelVipPackage->deleteInfo(['id' => $id]);
            
            if ($result) {
                return [RESULT_SUCCESS, '套餐删除成功'];
            } else {
                return [RESULT_ERROR, '套餐删除失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '套餐删除失败：' . $e->getMessage()];
        }
    }
    
    /**
     * VIP订单状态管理
     */
    public function vipStatus($data = [])
    {
        try {
            $id = $data['id'] ?? 0;
            $status = $data['status'] ?? 1;
            
            if (!$id) {
                return [RESULT_ERROR, 'VIP订单ID不能为空'];
            }
            
            $updateData = [
                'order_status' => $status,
                'update_time' => time()
            ];
            
            $result = $this->modelVipOrder->updateInfo(['id' => $id], $updateData);
            
            if ($result) {
                return [RESULT_SUCCESS, 'VIP状态更新成功'];
            } else {
                return [RESULT_ERROR, 'VIP状态更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, 'VIP状态更新失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 导出VIP订单列表
     */
    public function exportVipList($where = [])
    {
        try {
            // 设置别名和关联查询
            $this->modelVipOrder->alias_name = 'vo';
            $this->modelVipOrder->join = [
                ['user u', 'u.id = vo.user_id', 'LEFT']
            ];
            
            $field = 'vo.id,vo.order_no,vo.package_type,vo.package_name,vo.amount,vo.status,vo.transaction_id,vo.start_time,vo.end_time,vo.pay_time,vo.create_time,u.nickname,u.mobile';
            $order = 'vo.id desc';
            
            $list = $this->modelVipOrder->getList($where, $field, $order, false);
            
            // 清理属性，避免影响后续查询
            $this->modelVipOrder->join = [];
            $this->modelVipOrder->alias_name = '';
            
            // 处理导出数据
            $exportData = [];
            foreach ($list as $item) {
                $exportData[] = [
                    'ID' => $item['id'],
                    '订单号' => $item['order_no'],
                    '用户昵称' => $item['nickname'],
                    '手机号' => $item['mobile'],
                    '套餐类型' => $item['package_type'],
                    '套餐名称' => $item['package_name'],
                    '价格' => $item['amount'],
                    'VIP开始时间' => $item['start_time'] ? date('Y-m-d H:i:s', $item['start_time']) : '',
                    'VIP结束时间' => $item['end_time'] ? date('Y-m-d H:i:s', $item['end_time']) : '',
                    '支付方式' => 'wechat',
                    '支付状态' => $this->getOrderStatusText($item['status']),
                    '微信交易号' => $item['transaction_id'],
                    '支付时间' => $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '',
                    '创建时间' => $item['create_time'] ? date('Y-m-d H:i:s', $item['create_time']) : ''
                ];
            }
            
            // 这里应该调用导出功能，暂时返回数据
            return [RESULT_SUCCESS, '导出成功', $exportData];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '导出失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 根据订单激活用户VIP
     * @param array $orderInfo 订单信息
     * @return array
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function activateVipByOrder($orderInfo)
    {
        try {
            if (!$orderInfo || !isset($orderInfo['user_id'], $orderInfo['package_type'])) {
                return [RESULT_ERROR, '订单信息不完整'];
            }
            
            // 获取完整的订单信息（包含start_time和end_time）
            $fullOrderInfo = $this->modelVipOrder->getInfo(['id' => $orderInfo['id']], 'start_time,end_time,package_type');
            if (!$fullOrderInfo) {
                return [RESULT_ERROR, '订单信息获取失败'];
            }
            
            // 使用订单中记录的时间
            $startTime = date('Y-m-d H:i:s', $fullOrderInfo['start_time']);
            $endTime = date('Y-m-d H:i:s', $fullOrderInfo['end_time']);
            
            // 根据套餐类型设置VIP等级
            $packageType = $fullOrderInfo['package_type'];
            switch ($packageType) {
                case 'month':
                    $vipLevel = 1;
                    break;
                case 'quarter':
                    $vipLevel = 3;
                    break;
                case 'year':
                    $vipLevel = 12;
                    break;
                case 'three_year':
                    $vipLevel = 36;
                    break;
                default:
                    $vipLevel = 1;
            }
            
            // 更新用户VIP信息
            $userData = [
                'vip_level' => $vipLevel,
                'vip_start_time' => $startTime,
                'vip_expire_time' => $endTime,
                'update_time' => time()
            ];
            
            $result = $this->modelUser->updateInfo(['id' => $orderInfo['user_id']], $userData);
            
            if ($result) {
                return [RESULT_SUCCESS, 'VIP激活成功'];
            } else {
                return [RESULT_ERROR, 'VIP激活失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, 'VIP激活失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 根据订单取消用户VIP
     * @param array $orderInfo 订单信息
     * @return array
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function cancelVipByOrder($orderInfo)
    {
        try {
            if (!$orderInfo || !isset($orderInfo['user_id'])) {
                return [RESULT_ERROR, '订单信息不完整'];
            }
            
            // 取消用户VIP权限
            $userData = [
                'vip_level' => 0,
                'vip_start_time' => '',
                'vip_expire_time' => '',
                'update_time' => time()
            ];
            
            $result = $this->modelUser->updateInfo(['id' => $orderInfo['user_id']], $userData);
            
            if ($result) {
                return [RESULT_SUCCESS, 'VIP权限取消成功'];
            } else {
                return [RESULT_ERROR, 'VIP权限取消失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, 'VIP权限取消失败：' . $e->getMessage()];
        }
    }

    /**
     * 获取订单状态文本
     * @param int $status 状态值
     * @return string 状态文本
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function getOrderStatusText($status)
    {
        $statusMap = [
            0 => '未支付',
            1 => '已支付',
            2 => '已取消',
            3 => '已退款'
        ];
        
        return $statusMap[$status] ?? '未知状态';
    }

    /**
     * 根据订单号获取VIP订单信息
     */
    public function getVipOrderByNo($data = [])
    {
        try {
            $orderNo = $data['order_no'] ?? '';
            
            if (empty($orderNo)) {
                return [RESULT_ERROR, '订单号不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['order_no' => $orderNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户VIP订单列表
     */
    public function getUserVipOrders($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $status = $data['status'] ?? '';
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $where = ['user_id' => $userId];
            if (!empty($status)) {
                $where['order_status'] = $status;
            }
            
            $paginate = ['list_rows' => $limit, 'page' => $page];
            $list = $this->modelVipOrder->getList($where, true, 'id desc', $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 更新VIP订单状态
     */
    public function updateVipOrderStatus($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? 0;
            $status = $data['status'] ?? '';
            
            if (!$orderId) {
                return [RESULT_ERROR, '订单ID不能为空'];
            }
            
            if (empty($status)) {
                return [RESULT_ERROR, '状态不能为空'];
            }
            
            $updateData = [
                'order_status' => $status,
                'update_time' => time()
            ];
            
            // 如果是支付成功状态，更新支付时间
            if ($status == 'paid') {
                $updateData['pay_time'] = time();
            }
            
            $result = $this->modelVipOrder->updateInfo(['id' => $orderId], $updateData);
            
            if ($result) {
                return [RESULT_SUCCESS, '状态更新成功'];
            } else {
                return [RESULT_ERROR, '状态更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '状态更新失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取VIP订单统计
     */
    public function getVipOrderStatistics($data = [])
    {
        try {
            $startDate = $data['start_date'] ?? '';
            $endDate = $data['end_date'] ?? '';
            
            $where = [];
            if (!empty($startDate)) {
                $where['create_time'] = ['>=', strtotime($startDate)];
            }
            if (!empty($endDate)) {
                $where['create_time'] = ['<=', strtotime($endDate . ' 23:59:59')];
            }
            
            // 总订单数
            $totalOrders = $this->modelVipOrder->stat($where, 'count');
            
            // 已支付订单数
            $paidWhere = array_merge($where, ['status' => 'paid']);
            $paidOrders = $this->modelVipOrder->stat($paidWhere, 'count');
            
            // 总收入
            $totalIncome = $this->modelVipOrder->stat($paidWhere, 'sum', 'amount');
            
            // 待支付订单数
            $pendingWhere = array_merge($where, ['status' => 'pending']);
            $pendingOrders = $this->modelVipOrder->stat($pendingWhere, 'count');
            
            $statistics = [
                'total_orders' => $totalOrders,
                'paid_orders' => $paidOrders,
                'pending_orders' => $pendingOrders,
                'total_income' => $totalIncome ?: 0,
                'conversion_rate' => $totalOrders > 0 ? round(($paidOrders / $totalOrders) * 100, 2) : 0
            ];
            
            return [RESULT_SUCCESS, '获取成功', $statistics];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取待处理VIP订单
     */
    public function getPendingVipOrders($data = [])
    {
        try {
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            $where = ['status' => 'pending'];
            $paginate = ['list_rows' => $limit, 'page' => $page];
            
            $list = $this->modelVipOrder->getList($where, true, 'id desc', $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户最新VIP订单
     */
    public function getUserLatestVipOrder($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['user_id' => $userId], true, 'id desc');
            
            if (!$order) {
                return [RESULT_ERROR, '暂无订单记录'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取邀请人佣金统计
     */
    public function getInviterCommissionStats($data = [])
    {
        try {
            $inviterId = $data['inviter_id'] ?? 0;
            $startDate = $data['start_date'] ?? '';
            $endDate = $data['end_date'] ?? '';
            
            if (!$inviterId) {
                return [RESULT_ERROR, '邀请人ID不能为空'];
            }
            
            $where = [
                'inviter_id' => $inviterId,
                'status' => 'paid'
            ];
            
            if (!empty($startDate)) {
                $where['create_time'] = ['>=', strtotime($startDate)];
            }
            if (!empty($endDate)) {
                $where['create_time'] = ['<=', strtotime($endDate . ' 23:59:59')];
            }
            
            // 佣金总额
            $totalCommission = $this->modelVipOrder->stat($where, 'sum', 'commission_amount');
            
            // 佣金订单数
            $commissionOrders = $this->modelVipOrder->stat($where, 'count');
            
            $stats = [
                'total_commission' => $totalCommission ?: 0,
                'commission_orders' => $commissionOrders,
                'average_commission' => $commissionOrders > 0 ? round($totalCommission / $commissionOrders, 2) : 0
            ];
            
            return [RESULT_SUCCESS, '获取成功', $stats];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 更新微信支付信息
     */
    public function updateWechatPayInfo($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? 0;
            $wxOutTradeNo = $data['wx_out_trade_no'] ?? '';
            $wxTradeNo = $data['wx_trade_no'] ?? '';
            
            if (!$orderId) {
                return [RESULT_ERROR, '订单ID不能为空'];
            }
            
            $updateData = [
                'update_time' => time()
            ];
            
            if (!empty($wxOutTradeNo)) {
                $updateData['wx_out_trade_no'] = $wxOutTradeNo;
            }
            
            if (!empty($wxTradeNo)) {
                $updateData['wx_trade_no'] = $wxTradeNo;
            }
            
            $result = $this->modelVipOrder->updateInfo(['id' => $orderId], $updateData);
            
            if ($result) {
                return [RESULT_SUCCESS, '微信支付信息更新成功'];
            } else {
                return [RESULT_ERROR, '微信支付信息更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '微信支付信息更新失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 根据微信商户订单号获取订单
     */
    public function getByWxOutTradeNo($data = [])
    {
        try {
            $wxOutTradeNo = $data['wx_out_trade_no'] ?? '';
            
            if (empty($wxOutTradeNo)) {
                return [RESULT_ERROR, '微信商户订单号不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['wx_out_trade_no' => $wxOutTradeNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 根据微信交易号获取订单
     */
    public function getByWxTradeNo($data = [])
    {
        try {
            $wxTradeNo = $data['wx_trade_no'] ?? '';
            
            if (empty($wxTradeNo)) {
                return [RESULT_ERROR, '微信交易号不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['wx_trade_no' => $wxTradeNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 处理邀请佣金
     * @param array $vipOrder VIP订单信息
     * @return bool
     */
    private function processInviteCommission($vipOrder)
    {
        try {
            // 获取购买用户信息
            $user = $this->modelUser->getInfo(['id' => $vipOrder['user_id']]);
            if (!$user || !$user['inviter_id']) {
                return false; // 没有邀请人，无需处理佣金
            }
            
            // 获取邀请人信息
            $inviter = $this->modelUser->getInfo(['id' => $user['inviter_id']]);
            if (!$inviter) {
                return false; // 邀请人不存在
            }
            
            // 计算佣金比例（根据VIP套餐类型）
            $commissionRate = $this->getCommissionRate($vipOrder['package_type']);
            $commissionAmount = round($vipOrder['amount'] * $commissionRate, 2);
            
            if ($commissionAmount <= 0) {
                return false; // 佣金金额为0，无需处理
            }
            
            // 创建佣金记录
            $commissionData = [
                'user_id' => $inviter['id'],
                'from_user_id' => $user['id'],
                'order_id' => $vipOrder['id'],
                'amount' => $commissionAmount,
                'type' => 'vip_purchase',
                'description' => "邀请用户购买VIP套餐获得佣金",
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ];
            
            $commissionId = $this->modelCommissionRecord->updateInfo([], $commissionData);
            
            if ($commissionId) {
                // 更新邀请人余额：将余额记录的 related_id 关联到佣金记录ID，订单ID保留在描述中
                $this->updateInviterBalance($inviter['id'], $commissionAmount, $commissionId, $vipOrder['id']);
                return true;
            }
            
            return false;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('处理邀请佣金失败：' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 获取佣金比例
     * @param int $packageType VIP套餐类型
     * @return float
     */
    private function getCommissionRate($packageType)
    {
        return 0.50;
    }
    
    /**
     * 更新邀请人余额
     * @param int $inviterId 邀请人ID
     * @param float $amount 佣金金额
     * @param int $orderId 关联订单ID
     * @return bool
     */
    private function updateInviterBalance($inviterId, $amount, $commissionId, $orderId)
    {
        try {
            // 获取当前余额
            $currentBalance = $this->modelUser->getValue(['id' => $inviterId], 'available_amount');
            $currentTotalEarnings = $this->modelUser->getValue(['id' => $inviterId], 'total_earnings');
            
            // 更新余额
            $newBalance = $currentBalance + $amount;
            $newTotalEarnings = $currentTotalEarnings + $amount;
            
            $updateResult = $this->modelUser->updateInfo(
                ['id' => $inviterId],
                [
                    'available_amount' => $newBalance,
                    'total_earnings' => $newTotalEarnings,
                    'update_time' => time()
                ]
            );
            
            if ($updateResult) {
                // 记录余额变动
                $balanceData = [
                    'user_id' => $inviterId,
                    'type' => 'commission',
                    'amount' => $amount,
                    'balance_before' => $currentBalance,
                    'balance_after' => $newBalance,
                    'description' => "邀请用户购买VIP获得佣金，订单ID：{$orderId}",
                    'related_id' => $commissionId,
                    'status' => 1,
                    'create_time' => time(),
                    'update_time' => time()
                ];
                
                $this->modelBalanceRecord->updateInfo([], $balanceData);
                return true;
            }
            
            return false;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('更新邀请人余额失败：' . $e->getMessage());
            return false;
        }
    }
}
